package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 黑马程序员
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired(required = false)
    private OrderService orderService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {

        //1.获取登录的用户
        User user = (User) session.getAttribute("user");

        //2.调用业务生成订单
        orderService.submit(orders, user);

        //3.返回数据
        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R<Page<Orders>> findByPage(Integer page, Integer pageSize,
                                         @RequestParam(defaultValue = "") String number,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime beginTime,
                                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime endTime) {

        Page<Orders> ordersPage = orderService.findByPage(page, pageSize, number, beginTime, endTime);
        return R.success(ordersPage);
    }

    @GetMapping("/userPage")
    public R<Page<OrderDto>> findByUserPage(Integer page, Integer pageSize,HttpSession session) {
        User user = (User) session.getAttribute("user");
        Long id = user.getId();
        Page<OrderDto> ordersPage = orderService.findByUserPage(page,pageSize,id);
        return R.success(ordersPage);
    }
}
